'use strict'

module.exports = init;

//Global variables
var cacheStore;
var setting;
var defaultSetting = {
    checkDelay: 5000,
    expireTime: 'unlimited', //'unlimited' or a num
}


function init(opt) {
    setting = Object.assign({}, defaultSetting, opt)
    cacheStore = {}
    startAutoClearSession()

    return {
        getOrNewObjByKey,
    }
}

function updateExpireTime(id) {
    var obj = cacheStore[id]

    if (!obj)
        return

    if (isNaN(obj.timeBeforeExpire))
        return

    // console.log('Update expire time for '+id)

    obj.expireTime = new Date().getTime() + obj.timeBeforeExpire
}

/**
 * Get a obj by key,if not exist then create.If exist update expire time.
 * @param id
 * @param timeBeforeExpire
 * @returns {*}
 */
function getOrNewObjByKey(id, timeBeforeExpire) {

    if (cacheStore[id]) {
        updateExpireTime(id)
        return cacheStore[id]
    }


    var expireTime
    if (!isNaN(timeBeforeExpire)) {
        expireTime = new Date().getTime() + timeBeforeExpire
    } else {
        expireTime = setting.expireTime
    }
    cacheStore[id] = {id, expireTime, timeBeforeExpire}
    return cacheStore[id]
}

function startAutoClearSession() {

    var checkAndClear = function () {
        var now = new Date().getTime()

        for (var param in cacheStore) {
            var item = cacheStore[param]

            if (isNaN(item.expireTime))
                continue

            if (item.expireTime < now) {
                item.expireCallback = item.expireCallback || function () {
                }
                item.expireCallback(item)
                delete cacheStore[param]
            }
        }
    };

    (function start() {
        // console.log('check!')
        checkAndClear()
        setTimeout(start, setting.checkDelay)
    }())
}